package com.szosen.jkzj.activity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.provider.DocumentFile;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.github.mjdev.libaums.fs.UsbFileInputStream;
import com.github.mjdev.libaums.partition.Partition;
import com.szosen.application.MyApplication;
import com.szosen.jkzj.R;
import com.szosen.util.DatabaseTool;
import com.szosen.util.FileSaveUtil;
import com.szosen.util.JktjBitmapUtil;
import com.szosen.util.ToastTool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.szosen.application.MyApplication.ACTION_USB_PERMISSION;
import static com.szosen.util.DatabaseTool.getTFCard_BackupPath;


public class AdvancedSettingActivity extends BaseActivity {
    AlertDialog mDialog;
    TextView tv_lastBackupTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advanced_setting);
        tv_lastBackupTime = (TextView) findViewById(R.id.advanced_setting_tv_lastbackuptime);
        setTitleContent("【高级设置】");
    }

    /**
     * 直接显示备份的对话框，执行数据备份。
     */
    private void showExportDataDialog() {
        mDialog = showWarnDialog("正在备份数据，请勿退出！", false);
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
        DatabaseTool.exportDataBaseFile2SD(this, mHandler);
    }

    private int requestTFcard_code = 42;

    //失败时显示文件权限调用
    private void requestPermission() {
        try {
            //判断设备为4.4.4 19或者19以上的
            if (Build.VERSION.SDK_INT > 19) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                startActivityForResult(intent, requestTFcard_code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        if (resultCode == RESULT_OK && requestCode == requestTFcard_code) {
            Uri treeUri = resultData.getData();
            DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
            // List all existing files inside picked directory
            for (DocumentFile file : pickedDir.listFiles()) {
            }
//            try {
//                boolean bAndroid = pickedDir.findFile("Android").delete();
////                boolean b = pickedDir.findFile("Android").findFile("data").findFile("com.szosen.jkzj").findFile("村医版").delete();
//                if (b) {
////                pickedDir.findFile("Android").findFile("data").findFile("com.szosen.jkzj").createDirectory("村医版");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            //文件不存在则创建文件夹
            String desPath = getTFCard_BackupPath(context);
            if (!DatabaseTool.isTFCardDesExist(context)) {
                if (pickedDir.findFile("Android") != null) {
                    if (pickedDir.findFile("Android").findFile("data") != null) {
                        if (pickedDir.findFile("Android").findFile("data").findFile("com.szosen.jkzj") != null) {
                            if (pickedDir.findFile("Android").findFile("data").findFile("com.szosen.jkzj").findFile("村医版") == null) {
                                pickedDir.findFile("Android").findFile("data").findFile("com.szosen.jkzj").createDirectory("村医版");
                            }
                        } else {
                            pickedDir.findFile("Android").findFile("data").createDirectory("com.szosen.jkzj").createDirectory("村医版");
                        }
                    } else {
                        pickedDir.findFile("Android").createDirectory("data").createDirectory("com.szosen.jkzj").createDirectory("村医版");
                    }
                } else {
                    pickedDir.createDirectory("Android").createDirectory("data").createDirectory("com.szosen.jkzj").createDirectory("村医版");
                }
            }
            DocumentFile mainFilePath = pickedDir.findFile("Android").findFile("data").findFile("com.szosen.jkzj").findFile("村医版");
            for (DocumentFile file : mainFilePath.listFiles()) {
                boolean canWrite = file.canWrite();
                String name = file.getName();
//                System.out.println("文件" + name + ",可写？" + canWrite);
            }
            //获取权限后，执行数据备份操作。
            showExportDataDialog();
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //失败了
                case DatabaseTool.WHAT_EXPORTDATA_MESSAGE_FAILED:
                    dismissDialog();
                    ToastTool.showLong(context, "数据备份失败");
                    //授权失败或拒绝时调用请求权限
                    requestPermission();
                    break;
                //任务完成
                case DatabaseTool.WHAT_EXPORTDATA_MESSAGE_FINISH:
                    dismissDialog();
                    break;
                //拷贝成功
                case DatabaseTool.WHAT_EXPORTDATA_MESSAGE_SUCCESS:
                    dismissDialog();
                    ToastTool.showLong(context, "数据备份成功");
                    getLastBackupTime();
                    break;
                case DatabaseTool.WHAT_EXPORTDATA_MESSAGE_NO_SDCARD:
                    dismissDialog();
                    ToastTool.showLong(context, "未找到SD卡，请检查后再试！");
                    break;
                //失败了
                case DatabaseTool.WHAT_IMPORTDATA_MESSAGE_FAILED:
                    dismissDialog();
                    ToastTool.showLong(context, "数据导入失败");
                    break;
                //拷贝成功
                case DatabaseTool.WHAT_IMPORTDATA_MESSAGE_NO_BACKUPFILE:
                    dismissDialog();
                    ToastTool.showLong(context, "找不到备份文件");
                    break;
                case DatabaseTool.WHAT_IMPORTDATA_MESSAGE_SUCCESS:
                    dismissDialog();
                    ToastTool.showLong(context, "数据导入成功");
                    //强制重启软件
//                    Intent i = getBaseContext().getPackageManager()
//                            .getLaunchIntentForPackage(getBaseContext().getPackageName());
//                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    startActivity(i);
//                    Intent mStartActivity = new Intent(context, AdvancedSettingActivity.class);
//                    int mPendingIntentId = 123456;
//                    PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
//                    AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//                    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
//                    System.exit(0);
                    MyApplication.getInstance().exitApp();
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    ToastTool.showShort(context, "请重启软件，使数据还原生效！");
                    break;
            }
        }
    };

    private void dismissDialog() {
        //对话框正在显示，则隐藏
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    private void getFilesDirs() {
        try {
            final File[] dirs = getExternalFilesDirs(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 将数据导出至sd卡中
     * @param view
     */
    public void backupData(View view) {
        //直接导出sd卡
        showExportDataDialog();
    }

    /***
     * 从sd卡中导入数据
     * @param view
     */
    public void importData(View view) {
        mDialog = showPasswordDialog();
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
    }

    /***
     * 导出健康体检表
     * @param view
     */
    public void exportJKTJTable(View view) {
//        showDateSelectDialog();
        //测试将数据导出到U盘

    }

    private void registerReceiver() {
        // 监听otg插入 拔出
        IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mUsbReceiver, usbDeviceStateFilter);
        // 注册监听自定义广播
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, filter);
        executorService = Executors.newCachedThreadPool();// 30大小的线程池
    }

    private ExecutorService executorService;

    private void redDeviceList() {
        UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
        System.out.println("usb设备storageDevices长度：" + storageDevices.length);
        for (UsbMassStorageDevice device : storageDevices) {
            System.out.println("usb设备名称getDeviceName："
                    + device.getUsbDevice().getDeviceName());
            if (device.getUsbDevice().getVendorId() != 1027
                    && device.getUsbDevice().getVendorId() != 4817
                    && device.getUsbDevice().getProductId() != 24577) {
                if (usbManager.hasPermission(device.getUsbDevice())) {
                    readDevice(device);
                } else {
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(
                            this, 0, new Intent(ACTION_USB_PERMISSION), 0);
                    usbManager.requestPermission(device.getUsbDevice(),
                            pendingIntent);
                }
            }
        }
    }

    private UsbMassStorageDevice[] storageDevices;

    private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice) {
        for (UsbMassStorageDevice device : storageDevices) {
            if (usbDevice.equals(device.getUsbDevice())) {
                return device;
            }
        }
        return null;
    }

    private void readDevice(UsbMassStorageDevice device) {
        // before interacting with a device you need to call init()!
        try {
            device.init();
            // Only uses the first partition on the device
            Partition partition = device.getPartitions().get(0);
            FileSystem currentFs = partition.getFileSystem();
            // fileSystem.getVolumeLabel()
            // Log.d(TAG, "Capacity: " + currentFs.getCapacity());
            // Log.d(TAG, "Occupied Space: " + currentFs.getOccupiedSpace());
            // Log.d(TAG, "Free Space: " + currentFs.getFreeSpace());
            // Log.d(TAG, "Chunk size: " + currentFs.getChunkSize());
            UsbFile root = currentFs.getRootDirectory();// 获取根目录
            String deviceName = currentFs.getVolumeLabel();// 获取设备标签
            mUsbFile = root;
            addFile2List(deviceName);// 添加文件
        } catch (Exception e) {
            e.printStackTrace();
            // ToastTool.showLong(mInstance,"出错了"+e.getMessage());
            FileSaveUtil.saveTxtFile("error", "log.txt", e.getMessage());
        }
    }

    private void addFile2List(String deviceName) {// 添加文件和文件夹到gridView显示
        try {
            StringBuilder sb = new StringBuilder();
            for (UsbFile file : mUsbFile.listFiles()) {
                usbFiles.add(file);
                sb.append(file.getName() + "\n");
                String name = file.getName();
                if (!TextUtils.isEmpty(name) && name.equals("ASUPD")) {
                    // UsbFile ub = file.createFile("ASUPD.AS");
                    for (UsbFile fileSon : file.listFiles()) {
                        String name2 = fileSon.getName();
                        if (!TextUtils.isEmpty(name2)
                                && name2.equals("ASUPD.AS")) {
                            readFile(fileSon);
                            break;
                        }
                    }
                }
            }
            // ToastTool.showLong(mInstance,
            // "usbFiles.size="+usbFiles.size()+",名字="+usbFiles.get(0).getName()+"\n"+sb.toString());
            // Collections.sort(usbFiles, new Comparator<UsbFile>() {// 简单排序
            // 文件夹在前
            // // 文件在后
            // @Override
            // public int compare(UsbFile oFile1, UsbFile oFile2) {
            // if (oFile1.isDirectory())
            // return -1;
            // else
            // return 1;
            // }
            // });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    UsbFile mUsbFile;
    private List<UsbFile> usbFiles = new ArrayList<UsbFile>();
    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTION_USB_PERMISSION:
                    UsbDevice usbDevice = intent
                            .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,
                            false)) {
                        int vId = usbDevice.getVendorId();
                        if (usbDevice != null && vId != 1027) {
                            readDevice(getUsbMass(usbDevice));
                        }
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_ATTACHED:
                    UsbDevice device_add = intent
                            .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    int vId = device_add.getVendorId();
                    int pId = device_add.getProductId();
                    System.out.println("插入了U盘vId=" + vId + "pId=" + pId);
                    if (device_add != null && vId != 1027) {
                        redDeviceList();
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED:
                    // UsbDevice device_remove = intent
                    // .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    try {
                        if (!TextUtils.isEmpty(updateJianhuyi_FilePath)) {
                            final File f = new File(updateJianhuyi_FilePath);
                            if (f.exists()) {
                                f.delete();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };
    private String updateJianhuyi_FilePath = "";

    private void readFile(final UsbFile uFile) {
        String sdPath = FileSaveUtil.getSDCardPath();// 获取sd根目录 创建一个同名文件
        String filePath = sdPath + uFile.getName();
        updateJianhuyi_FilePath = filePath;
        final File f = new File(filePath);
        // if (f.exists()) {
        //
        // } else {
        try {
            f.createNewFile();
            // 设置视图
            // 执行线程
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileOutputStream os = new FileOutputStream(f);
                        InputStream is = new UsbFileInputStream(uFile);
                        redFileStream(os, is);
                    } catch (final Exception e) {
                        e.printStackTrace();
                        FileSaveUtil.saveTxtFile("dd",
                                "executorServicelog.txt", e.getMessage());
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        // }
    }

    private void redFileStream(OutputStream os, InputStream is)
            throws IOException {
        /**
         * 写入文件到U盘同理 要获取到UsbFileOutputStream后 通过 f.createNewFile();调用 在U盘中创建文件
         * 然后获取os后 可以通过输出流将需要写入的文件写到流中即可完成写入操作
         */
        int bytesRead = 0;
        byte[] buffer = new byte[1024 * 8];
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.flush();
        os.close();
        is.close();
        // ToastTool.showLong(mInstance, "写完文件了");
    }

    private static boolean isMountSDCard = false;

    public class UsbStatesReceiver extends BroadcastReceiver {
        public static final int USB_STATE_MSG = 0x00020;
        public static final int USB_STATE_OFF = 0x00022;
        Context context = null;

        public UsbStatesReceiver(Context context) {
            this.context = context;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)
                    || intent.getAction().equals(Intent.ACTION_MEDIA_CHECKING)) {
                isMountSDCard = true;
            } else if (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)
                    || intent.getAction().equals(Intent.ACTION_MEDIA_REMOVED)) {
                isMountSDCard = false;
            }
            String path = intent.getDataString();
            if (!TextUtils.isEmpty(path)) {
                String pathString = path.split("file://")[1];
                File otgFile = new File(pathString);
                if (otgFile.exists()) {
                    File[] files = otgFile.listFiles();
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < files.length; i++) {
                        sb.append(files[i].getAbsolutePath() + "\n");
                    }
                    // ToastTool.showLong(mContext, sb.toString());
                }
            }
            // ToastTool.showLong(mContext, intent.getDataString());
        }

        ;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getLastBackupTime();
    }

    private void getLastBackupTime() {
        String backupPath = getTFCard_BackupPath(context);
        if (TextUtils.isEmpty(backupPath)) {
            tv_lastBackupTime.setText("未找到SD卡，请检查SD卡是否插入");
        } else {
            //获取上次备份的时间
            String lastBackupTime = DatabaseTool.getBackupTimeFromTFCard(AdvancedSettingActivity.this);
            if (!TextUtils.isEmpty(lastBackupTime)) {
                tv_lastBackupTime.setText("上次备份时间：" + lastBackupTime);
            } else {
                tv_lastBackupTime.setText("上次备份时间：" + "无");
            }
        }

    }

    /***
     * 显示一个警告的窗口。
     */
    private AlertDialog showWarnDialog(String message, boolean setOK) {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                AdvancedSettingActivity.this);
        LayoutInflater inflater = (LayoutInflater) AdvancedSettingActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout tl = (LinearLayout) inflater.inflate(
                R.layout.activityadvancedsetting_item_dialog, null);
        TextView tv_message = (TextView) tl.findViewById(R.id.dialog_tv_message);
        tv_message.setText(message);
        builder.setView(tl);
        builder.setTitle("警告");
//        builder.setNegativeButton("取消", null);
        if (setOK) {
            builder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
        }
        builder.setCancelable(false);
        return builder.create();
    }

    private void showDateSelectDialog() {
        mDialog = (AlertDialog) new DateSelectDialog(context).create();
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
    }

    private class DateSelectDialog extends AlertDialog.Builder {
        private DatePicker datePicker;

        public DateSelectDialog(Context context) {
            super(context);
            LayoutInflater inflater = LayoutInflater.from(context);
            View view = inflater.inflate(R.layout.dialog_date_selector, null);
            datePicker = (DatePicker) view.findViewById(R.id.date_picker);
            this.setView(view);
            this.setTitle("日期选择");
            this.setPositiveButton("打印日期", positivelistener);
            this.setNeutralButton("打印全部", neutrallistener);
            this.setNegativeButton("取消", null);
        }

        public String getDate() {
            int day = datePicker.getDayOfMonth();
            int month = datePicker.getMonth() + 1;
            int year = datePicker.getYear();
            final Calendar calendar = Calendar.getInstance();
            final int mSecond = calendar.get(Calendar.SECOND);// 获取当前的分钟数
            String mYear = "";
            String mMonth = "";
            String mDay = "";
            if (month >= 0 && month < 10) {
                mMonth = "0" + month;
            } else {
                mMonth = "" + month;
            }
            if (day >= 0 && day < 10) {
                mDay = "0" + day;
            } else {
                mDay = "" + day;
            }
            mYear = year + "";
            String date = mYear + "-" + mMonth + "-" + mDay;
            return date;
        }

        public DateSelectDialog(Context context,
                                String posNote, String neuNote, String negNote, DialogInterface.OnClickListener mpositivelistener, DialogInterface.OnClickListener mneutrallistener) {
            this(context);
            this.setTitle("选择打印日期");
            this.setPositiveButton(posNote, mpositivelistener);
            this.setNeutralButton(neuNote, mneutrallistener);
            this.setNegativeButton(negNote, null);
        }

        //打印单个日期的按钮
        final DialogInterface.OnClickListener positivelistener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String date = getDate();
                System.out.println("打印日期按钮，你选择的日期是" + date);
                JktjBitmapUtil.exportJKTJTable(context, null, date, false);
            }
        };
        final DialogInterface.OnClickListener neutrallistener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.out.println("全部打印按钮，你选择的日期是");
                JktjBitmapUtil.exportJKTJTable(context, null, "", true);
            }
        };
    }

    private AlertDialog showPasswordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                AdvancedSettingActivity.this);
        LayoutInflater inflater = (LayoutInflater) AdvancedSettingActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout tl = (LinearLayout) inflater.inflate(
                R.layout.activity_tiwen_dialog_chancedevice, null);
        final ListView lv_btdevice_lists = (ListView) tl
                .findViewById(R.id.lv_btdevice_lists);
        final LinearLayout ll_password = (LinearLayout) tl
                .findViewById(R.id.ll_tiwen_password);
        final EditText et_password = (EditText) ll_password
                .findViewById(R.id.et_tiwen_password);
        final TextView tv_inputPWD = (TextView) ll_password
                .findViewById(R.id.tv_tiwen_password_pleaseInputPWD);
        tv_inputPWD.setText("请输入导入数据的权限密码");
        ll_password.setVisibility(View.VISIBLE);
        lv_btdevice_lists.setVisibility(View.GONE);
        builder.setView(tl);
        builder.setTitle("请输入密码：");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (ll_password.getVisibility() != View.VISIBLE) {
                    return;
                }
                String password = et_password.getText().toString();
                if (!TextUtils.isEmpty(password)
                        && password.equals(DatabaseTool.EXPORTDATA_PERMISSION_PASSWORD)) {
                    //开始导入数据
                    mDialog = showWarnDialog("正在导入数据，请勿退出！", false);
                    if (!mDialog.isShowing()) {
                        mDialog.show();
                    }
                    DatabaseTool.importDataFileFromSD(AdvancedSettingActivity.this, mHandler);
                } else {
                    ToastTool.showShort(context, "密码不正确！");
                }
            }

        });
        builder.setNegativeButton("取消", null);
        return builder.create();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }
}
